<!-- 合同基础设置 -->
<template>
  <div class="step2">
    <!-- <RichTextTemplate style="flex: 1" v-model:codes="richTextTemplateValue.codes" v-model:text="richTextTemplateValue.text" :height="600" /> -->
    <!-- ----------------------------------------------------------- -->
    <!-- 内容 -->
    <div class="wrap">
      <!-- 左侧文档区 -->
      <section>
        <a-tabs @change="tabsChange" v-model:active-key="choiceTemId">
          <a-tab-pane v-for="item in temList" :key="item.uuid" :title="item.name">
          </a-tab-pane>
        </a-tabs>
        <RichTextNew v-model:content="temObj.text" :name="`rich${temObj.uid}`" ref="refRichTextNew" v-if="!fileShow"></RichTextNew>
      </section>
      <!-- 编辑区 -->
      <section class="control" v-if="!fileShow">
        <a-scrollbar style="height: calc(100vh - 260px); overflow: auto">
          <!-- 已选人员 -->
          <section>
            <h3>已选人员</h3>
            <a-space wrap>
              <a-radio-group v-model="choiceUserId" @change="userChange">
                <a-radio v-for="item in userList" :key="item.id" :value="item.id">
                  <template #radio="{ checked }">
                    <a-tag size="large" :class="{ 'custom-radio-card-checked': checked }" :checked="checked" class="custom-radio-card" checkable>{{ item.name }}</a-tag>
                  </template>
                </a-radio>
              </a-radio-group>
            </a-space>
            <a-divider />
          </section>
          <!-- 搜索模块 -->
          <a-input-search v-model="searchVal" search-button @input="onSearch" @press-enter="onSearch" placeholder="快速搜索变量"></a-input-search>
          <!-- 按钮区 -->
          <section v-for="item in currControlData" :key="item.id">
            <h3>{{ item.subDetail.cnName }}</h3>
            <a-space wrap>
              <a-button v-for="(item2, index2) in item.subDetail.subRelDetail" :key="item2.id" @click="inputLabel(item2, index2)">{{ item2.ctlCnName }}
              </a-button>
            </a-space>
          </section>
        </a-scrollbar>
      </section>
    </div>
    <!-- 本地合同查看器 -->
    <FilePreview ref="previewFileRef" :style="'padding:20px;min-height:' +(paper.a4.height - 40)+'px'" v-if="fileShow" class="body" :file="previewFile">
    </FilePreview>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { cloneDeep } from 'lodash';
import { GetBusinessModalData } from '@/apis/controltotal';
import { changeControlData } from '@/utils/control';
import { paper } from '@/utils/printAndPdf';
import FilePreview from './FilePreview.vue';

let choiceTemId = ref(''); //当前合同 储存当前选中tab的uid
let choiceUserId = ref(0); //当前用户 被选中的
let temObj = reactive<any>({}); //合同对象
let temList = ref<any[]>([]); //合同
let userList = ref<any[]>([]); //人员
let itemRefs: any = {}; // 储存动态生成的富文本ref
const searchVal = ref(''); //输入框
const currControlData = ref<any>([]); // 储存当前控件信息
// tab选项初始数据
let controlList: any = ref();
// 组件ref
const refRichTextNew = ref(null);
// 刷新组件
const fileShow = ref(false);
// 组件数据
let previewFile = reactive({
  id: '',
  fileName: '',
  downloadUrl: ''
});
let originControlData = ref([]); // 储存原始控件信息

defineExpose({
  setData({ templateObj, templateList, users }: any) {
    // console.log('templateObj', templateObj);
    // console.log('templateList', templateList);
    // console.log('users', users);

    temList.value = templateList;
    userList.value = users;
    choiceTemId.value = templateList[0].uuid;
    choiceUserId.value = users[0].id;
    // console.log('被选择的用户', choiceUserId.value);
    // console.log('被选择的合同', choiceTemId.value);
    // console.log('temList.value', temList.value);

    for (const key in temObj) {
      delete temObj[key];
    }
    Object.assign(temObj, templateList[0]);
    // console.log('temObj', temObj);
    getCodes();
  },
  async getData() {
    return {
      templateObj: temObj,
      templateList: temList.value,
      userList: userList.value
    };
  }
});
// 获取控件信息
const getControlData = async () => {
  const { funcCtlInfos } = (await GetBusinessModalData({
    funcCode: 'SER_FUNC751D0BFF5DF442209D437EE9A581693E'
  })) as any;
  controlList.value = changeControlData(funcCtlInfos, 'ctlDetail');
  currControlData.value = cloneDeep(funcCtlInfos.children);
  originControlData.value = funcCtlInfos.children;
  console.log('originControlData---------',originControlData.value);
  
};
getControlData();

// 搜索按钮事件
const onSearch = () => {
  currControlData.value = [];
  if (searchVal.value === '') {
    currControlData.value = cloneDeep(originControlData.value);
  } else {
     for (let item of originControlData.value) {
      item.subDetail.subRelDetail.forEach((item2: any) => {
        if (item2.ctlCnName.includes(searchVal.value)) {
          // 判断如果该控件所属的子集不存在，则创建一个子集，否则直接将控件信息赋值给subRelDetail
          if (
            currControlData.value[currControlData.value.length - 1]?.id !==
            item.id
          ) {
            currControlData.value.push({
              id: item.id,
              subDetail: {
                cnName: item.subDetail.cnName,
                subRelDetail: []
              }
            });
          }
          currControlData.value[
            currControlData.value.length - 1
          ].subDetail.subRelDetail.push(item2);
        }
      });
    }
  }
};

// 切换模版
const tabsChange = async (key: string) => {
  const foundIndex = await temList.value.findIndex(
    (item) => item.uuid === temObj.uuid
  );
  //  temObj.text;
  temList.value[foundIndex].text = temObj.text;
  // 将旧tabs替换掉
  choiceTemId.value = key;
  // 循环合同找到选择到的对应的uuid值的合同
  const foundItem = temList.value.find(
    (item) => item.uuid === choiceTemId.value
  );
  for (const key in temObj) {
    delete temObj[key];
  }
  Object.assign(temObj, foundItem);
  console.log('回显的pdf数据', temObj.codes);
  getCodes();
};
// 判断是本地文件
const getCodes = () => {
  if (!temObj.codes) {
    previewFile.id = temObj.fileId;
    previewFile.fileName = temObj.fileName;
    previewFile.downloadUrl = temObj.fileUrl;
    fileShow.value = true;
  } else {
    fileShow.value = false;
  }
};

// 动态设置富文本ref
const setItemRef = (el: any, uid: number) => {
  itemRefs[uid] = el;
};
// 选择人员
const userChange = (key: number) => {
  currUserId.value = key;
  currTab.value = tabs.data[currUserId.value][0].uid;
  currIndex = 0;
};
// 新增tab
const inputLabel = (item: any, ind: number) => {
  const arr = temObj.codes.split(',').filter(Boolean);
  // console.log('arr在这里', arr, ind);
  if (arr?.length !== 0) {
    if (!arr?.some((ele: any) => ele === controlList.value[ind].ctlCode)) {
      arr?.push(controlList.value[ind].ctlCode);
    }
  } else {
    arr?.push(controlList.value[ind].ctlCode);
  }
  // console.log('controlList在这里', controlList.value);
  temObj.codes = arr.join(',');
  const tag = `&nbsp;<span style="text-decoration: underline; color: #3598db; font-size: 12pt;">#${item.ctlCnName}#</span>&nbsp;`;
  nextTick(() => {
    temObj.text += tag;
  });
};

// let richTextTemplateValue = computed({
//   get() {
//     if (!choiceTemId.value || !choiceUserId.value) return {};
//     return temObj[choiceUserId.value + '-' + choiceTemId.value];
//   },
//   set(val) {
//     temObj[choiceUserId.value + '-' + choiceTemId.value] = { ...val };
//   }
// });
</script>

<style lang="less" scoped>
.body {
  margin: 0 auto;
  text-align: center;
  word-wrap: break-word;
  margin-bottom: 70px;
  box-shadow: 0px 0px 5px var(--color-neutral-6);
  // transform: scale(1.4);
  width: 80%;
}
.wrap {
  width: 100%;
  display: grid;
  grid-template-columns: 3fr 1fr;

  .control {
    max-width: 300px;
    padding: 10px 20px 0px;

    section {
      h3 {
        font-weight: 700;
        height: 56px;
        line-height: 56px;
        &::before {
          content: '';
          display: inline-block;
          width: 6px;
          height: 40%;
          margin-right: 10px;
          background: #165dff;
          position: relative;
          top: 7px;
          border-radius: 3px;
        }
      }

      .custom-radio-card {
        background-color: #fff;
      }
      .custom-radio-card:hover,
      .custom-radio-card-checked {
        border-color: rgb(var(--primary-6));
      }
    }
  }
}
.step2 {
  .tab {
    display: flex;
    justify-content: left;
    align-items: center;
    height: 25px;
    margin-bottom: 10px;
    .title {
      font-size: 16px;
      margin-right: 10px;
    }
  }
}
</style>
